<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="900px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" :clearable="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="餐品类型" prop="typeId">
            <el-select v-model="formData.typeId" placeholder="请输入餐品类型">
              <el-option
                v-for="dict in dishTypeList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="价格" prop="price">
            <el-input v-model="formData.price" placeholder="请输入价格" :clearable="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="辣味" prop="spicy">
            <el-input v-model="formData.spicy" placeholder="请输入辣味" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="口感" prop="taste">
            <el-input v-model="formData.taste" placeholder="请输入口感" :clearable="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="口味" prop="flavor">
            <el-input v-model="formData.flavor" placeholder="请输入口味" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              rows="3"
              type="textarea"
              placeholder="请输入描述"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传照片">
            <UploadImg v-model="formData.imgUrl" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="禁忌人群" prop="taboo">
            <el-checkbox-group v-model="formData.taboo">
              <el-checkbox
                v-for="dict in getIntDictOptions(DICT_TYPE.RESTAURANT_DISH_TABOO)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddMaterial">添加原料</el-button>
      <el-button @click="clickDeleteMaterial">删除原料</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :data="formData.materials"
      save-key="RestaurantDishEdit"
      @row-click="handleRowClick"
      height="400"
    >
      <template #name="{ row }">
        <el-input class="!w-70px" v-model="row.name" />
      </template>
      <template #heat="{ row }">
        <InputNumber class="!w-100px" v-model="row.heat" type="decimal" />
      </template>
      <template #protein="{ row }">
        <InputNumber class="!w-100px" v-model="row.protein" type="decimal" />
      </template>
      <template #fat="{ row }">
        <InputNumber class="!w-100px" v-model="row.fat" type="decimal" />
      </template>
      <template #carbohydrate="{ row }">
        <InputNumber class="!w-100px" v-model="row.carbohydrate" type="decimal" />
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="RestaurantDishEdit" lang="ts">
import * as RestaurantDishApi from '@/api/restaurant/dish'
import * as RestaurantDishModel from '@/model/restaurant/dish/RestaurantDish'
import * as RestaurantDishMaterialModel from '@/model/restaurant/dish/RestaurantDishMaterial'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
interface RestaurantDishMaterialEdit extends RestaurantDishMaterialModel.RestaurantDishMaterial {
  operateType: string
}
interface RestaurantDishEdit extends RestaurantDishModel.RestaurantDish {
  materials: RestaurantDishMaterialEdit[]
}
const { t } = useI18n()
const message = useMessage()
let formType = ''
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const dishTypeList = ref()
const formData = ref<RestaurantDishEdit>({
  id: 0,
  name: '',
  typeId: undefined,
  price: 0,
  spicy: '',
  taste: '',
  flavor: '',
  description: '',
  imgUrl: '',
  taboo: [],
  materials: []
})
const formRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  typeId: [{ required: true, message: '请输入餐品类型', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '名称',
    prop: 'name',
    slot: 'name'
  },
  {
    label: '热量（千克）',
    prop: 'heat',
    slot: 'heat',
    minWidth: '100'
  },
  {
    label: '蛋白质（g）',
    prop: 'protein',
    slot: 'protein'
  },
  {
    label: '脂肪（g）',
    prop: 'fat',
    slot: 'fat'
  },
  {
    label: '碳水化合物（g）',
    prop: 'carbohydrate',
    slot: 'carbohydrate'
  }
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  dishTypeList.value = await RestaurantDishApi.listQueryDishType()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RestaurantDishApi.singleGet(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: 0,
    name: '',
    typeId: undefined,
    price: 0,
    spicy: '',
    taste: '',
    flavor: '',
    description: '',
    imgUrl: '',
    taboo: [],
    materials: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  let uniqueMaterials = Array.from(
    new Set(
      formData.value.materials.map((material) => {
        return material.name
      })
    )
  )
  if (uniqueMaterials.length != formData.value.materials.length) {
    message.error('存在重复的菜品原料')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RestaurantDishEdit
    if (formType === 'create') {
      await RestaurantDishApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await RestaurantDishApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

const clickAddMaterial = () => {
  formData.value.materials.push({
    id: 0,
    dishId: formType === 'create' ? 0 : formData.value.id,
    name: '',
    heat: 0,
    protein: 0,
    fat: 0,
    carbohydrate: 0,
    operateType: 'new'
  })
}

const clickDeleteMaterial = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的物资')
    return
  }
  if (formType === 'create' || tableCurrentRow.value.id == '') {
    const index = formData.value.materials.indexOf(tableCurrentRow.value)
    formData.value.materials.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
}
</script>
